package com.qf.shopping.servlet.filter;

import com.qf.shopping.common.StaticResource;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**设置访问权限
 * @author 三旬
 * @version 1.0  2022/9/20
 */
// 用户在访问后台资源时拦截，判断用户是否登录，登录了就放行，没有登录就跳转登录页面。
// 对后台资源访问的认证操作(后台相关资源时判断用户是登录了)
// 只拦截后台相关的操作
@WebFilter({"/UserController/*","/AdminController/*","/ProductTypeController/*","/ProductController/*","/back/*","/images/*","/BackOrderController/*"})
public class VisitFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //类型转换
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        //获取请求路径中的session对象
        Object name = request.getSession().getAttribute("sysUser");
        //判断session 中是否存在用户名，存在放行，不存在拦截重定向到登录页面
        //设置登陆页面不会再次重定向
        String path = request.getRequestURI();
        if(name != null || StaticResource.checkUrl(path)){
            filterChain.doFilter(request,response);
        }else{
            response.sendRedirect("/backLogin.jsp");
        }
    }

    @Override
    public void destroy() {

    }
}
